# -*- coding: utf-8 -*-
import os
import errno
import traceback
import compileall
import shutil


def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5 (except OSError, exc: for Python <2.5)
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


def dir_copytree(src, dst):
    names = os.listdir(src)
    # 目标文件夹不存在，则新建
    if not os.path.exists(dst):
        os.mkdir(dst)
    # 遍历源文件夹中的文件与文件夹
    for name in names:
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            # 是文件夹则递归调用本拷贝函数，否则直接拷贝文件
            if os.path.isdir(srcname):
                dir_copytree(srcname, dstname)
            else:
                name_list = name.rsplit('.', 1)
                if len(name_list) <= 1:
                    ext_name = ''
                else:
                    ext_name = name_list[1]
                if ext_name == 'pyc':
                    print 'move ', srcname
                    shutil.move(srcname, dst)
                elif ext_name != 'py':
                    print 'copy ', srcname
                    shutil.copy2(srcname, dst)
        except:
            traceback.format_exc()
            raise


def run():
    cwd_path = os.getcwd()
    img_dirs = [
        '/data/shitouren/img/saved',
        '/data/shitouren/img/failed',
        '/data/shitouren/map/saved',
        '/data/shitouren/map/failed',
    ]
    replace_test_files = [
        (
            './test/shitouren/controls/data_pool_mysql_test.pyc',
            './test/shitouren/controls/data_pool_mysql.pyc',
        ),
        (
            './test/shitouren/controls/mongo_test.pyc',
            './test/shitouren/controls/mongo.pyc',
        ),
        (
            './test/shitouren/config/environment_test.pyc',
            './test/shitouren/config/environment.pyc',
        ),
        (
            './test/shitouren/shitouren.pyc',
            './test/shitouren/test.pyc',
        ),
    ]

    # 创建图片目录
    for img_dir in img_dirs:
        mkdir_p(img_dir)

    # 编译python文件
    compileall.compile_dir(os.path.join(cwd_path, 'app'))

    # 删除老的文件
    shutil.rmtree(os.path.join(cwd_path, 'test/shitouren'))
    # 移动pyc文件，复制非py文件
    dir_copytree(os.path.join(cwd_path, 'app'),
                 os.path.join(cwd_path, 'test/shitouren'))

    # replace db instance with test
    for replace_file in replace_test_files:
        shutil.copy2(os.path.join(cwd_path, replace_file[0]),
                     os.path.join(cwd_path, replace_file[1]))

    # cp -f ./test/shitouren/controls/data_pool_mysql_test.pyc ./test/shitouren/controls/data_pool_mysql.pyc
    # cp -f ./test/shitouren/controls/mongo_test.pyc ./test/shitouren/controls/mongo.pyc
    # cp -f ./test/shitouren/config/environment_test.pyc ./test/shitouren/config/environment.pyc
    #
    # ps aux | grep test.pyc | grep -v grep | awk '{print $2}' | xargs kill -9
    # #ps aux | grep socket_server.pyc | grep "port=${websocket_port}" | awk '{print $2}' | xargs kill -9
    #
    # PYTHONPATH=./test/shitouren/ nohup python ./test/shitouren/test.pyc port=8000 >> /web/logs/test.log 2>&1 &
    # #nohup python ./test/shitouren/socket_server.pyc port=${websocket_port} &
    #
    # tail -f /web/logs/test.log


if __name__ == '__main__':
    run()
